React Routers – Types & Implementations

React Routers – Types & Implementations

Clock Icon2021.10.05

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Introduction

React Router is a library used for routing in React. In a given React Application,

  • It enables the navigation among displays of various components based on their action or request
  • Allows modifying the browser URL
  • Keeps the UI display in sync with the URL

It is used to define multiple routes in an application. When a user types a specific URL into the browser, and if this URL path matches any route specified inside the router file, the user will be redirected to that particular route.

To understand the React Router funtionality, first we create a react app by using:

npx create-react-app demo-route

Next, we install the library using :

npm install react-router-dom

Types of React Routers

To get into the basics, there are three primary categories of components in React Router:

  1. Routers, like BrowserRouter and HashRouter
  2. Route matchers, like Route and Switch
  3. Navigation(Route changers), like Link, NavLink, and Redirect

All of the components that we use in the web application should be imported from react-router-dom as:

import { BrowserRouter, Route, Link } from "react-router-dom";

Building the sample React application

We are building a demo application that will contain two page components: Home component and FAQs component. We will use React Router to navigate between these two components. Here, Link provides declarative, accessible navigation in our application. Switch element checks its children Route elements and renders the first one whose path matches the current URL. Switch can have multiple routes, but only one of them should be rendered at a time. The sample React Application can be written as : Route.js

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

export default function RouterExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/faq">FAQ</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/faq">
            <Faq />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return (
    <div>
      <h2>Home</h2>
      <h5>This is the Home page.</h5>
    </div>
  );
}

function Faq() {
  return (
    <div>
      <h2>FAQs</h2>
      <h5>This is the FAQs page. </h5>
    </div>
  );
}

The below image shows the Home Page Component when routed from "HOME" Link.

The below image shows the FAQs Page Component when routed from "FAQ" Link.

React Router with Hooks

React Router with a few hooks will let us access the state of the router and helps with navigation from inside the components.

One such hook used is useHistory. The useHistory hook gives us access to the history instance that we may use to navigate. The useHistory hook can be implemented as:

import { useHistory } from "react-router-dom";

function FaqButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/faq");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go to FAQs
    </button>
  );
}

Other hooks are : useLocation, useParams, useRouteMatch.

Implementing BrowserRouter

The BrowserRouter uses the HTML5 history API (pushState, replaceState, and popState event) to keep our UI display in sync with the URL. For example, by considering a page component called "Dashboard" and it can further be redirected to 2-page components - Scores, Faqs. It can be implemented as:

<BrowserRouter basename="/dashboard">
    <Link to="/scores"/> 
    <Link to="/faqs"/> 
</BrowserRouter>

Here, The first Link element renders like the a element functionality to redirect to "/dashboard/scores". The second Link element redirects to "/dashboard/faqs".

NavLink is another version of the Link element that will add styling attributes to the rendered element when it matches the current URL.

<NavLink to="/faq" activeStyle={{ fontWeight: "bold", color: "green" }}>
  Go To FAQs
</NavLink>

Here, the active Style object is used when styles are to be applied to the element when it is active.

There are many other ways in which routing can be implemented. These include, HashRouter, MemoryRouter, prompt etc. The correct elements can be used depending on the application requirements.

Conclusion

The blog begins with the Introduction to React Routers. Later, the different types of React Routers are being discussed. This information can be used to build applications with easy navigation. By using the React Routers library, it's easy to route between the components of our React application and makes it organized.

Happy Coding!

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.